package com.wqd.wemedia.service.impl;

import com.wqd.apis.schedule.IScheduleClient;

import com.wqd.common.enums.TaskTypeEnum;
import com.wqd.model.schedule.dto.Task;
import com.wqd.model.wemedia.pojos.WmNews;
import com.wqd.utils.common.ProtostuffUtil;
import com.wqd.wemedia.service.WmNewsAutoScanService;
import com.wqd.wemedia.service.WmNewsTaskService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;


    /**
     * 添加任务到延迟队列
     * @param id  文章的id
     * @param publishTime  发布的时间  可以做为任务的执行时间
     */
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中----begin");

        //创建一个任务
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        WmNews wmNews = new WmNews();
        wmNews.setId(id);

        //把wmNews序列化到task中
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        scheduleClient.addTask(task);

        log.info("添加任务到延迟服务中----end");
    }

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 消费延迟队列数据
     */
    @Scheduled(fixedRate = 50000)  //50s
    @Override
    @SneakyThrows
    public void scanNewsByTask() {
        log.info("文章审核----消费任务开始执行----begin");
        //拉取任务
        Task task = scheduleClient.pullTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(task!=null && task.getParameters().length > 0){
            byte[] bytes = task.getParameters();
            //将任务中的数据反序列化为wmNews
            WmNews wmNews = ProtostuffUtil.deserialize(bytes, WmNews.class);
            //调用自动审核业务
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }
        log.info("文章审核----消费任务完毕----end");
    }
}
